package org.jeecg.modules.app.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.RequiredArgsConstructor;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.config.TenantContext;
import org.jeecg.common.model.EnumDictOption;
import org.jeecg.common.util.JacksonUtil;
import org.jeecg.common.util.MessageUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.app.entity.AppClient;
import org.jeecg.modules.app.entity.AppInfo;
import org.jeecg.modules.app.entity.AppUpgrade;
import org.jeecg.modules.app.enums.AppBizTypeEnums;
import org.jeecg.modules.app.enums.AppPlatformTypeEnums;
import org.jeecg.modules.app.enums.AppTypeEnums;
import org.jeecg.modules.app.mapper.AppClientMapper;
import org.jeecg.modules.app.mapper.AppInfoMapper;
import org.jeecg.modules.app.mapper.AppUpgradeMapper;
import org.jeecg.modules.app.service.IAppInfoService;
import org.jeecg.modules.rental.constant.RentalCacheConstant;
import org.jeecg.modules.rental.entity.RentalConfig;
import org.jeecg.modules.rental.enums.RentalConfigEnums;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Description: 应用信息
 * @Author: sean
 * @Date:   2024-12-16
 * @Version: V1.0
 */
@Service
@RequiredArgsConstructor
public class AppInfoServiceImpl extends ServiceImpl<AppInfoMapper, AppInfo> implements IAppInfoService {

    private final CacheManager cacheManager;
    private final AppClientMapper clientMapper;
    private final AppUpgradeMapper upgradeMapper;

    @Override
    public IPage<AppInfo> selectJoinPage(Page page, Wrapper wrapper) {
        IPage<AppInfo> pageList = baseMapper.selectJoinPage(page, wrapper);
        if(ObjectUtil.isNotEmpty(pageList) && ObjectUtil.isNotEmpty(pageList.getRecords())){
            pageList.getRecords().forEach(item->{
                AppBizTypeEnums bizTypeEnums = AppBizTypeEnums.getEnumByValue(item.getAppType());
                if(ObjectUtil.isNotEmpty(bizTypeEnums)){
                    item.setAppTypeTxt(MessageUtils.message(bizTypeEnums.getRemark()));
                }
            });
        }
        return pageList;
    }

    @Override
    public List<EnumDictOption> selectOption(AppClient appClient) {
        return baseMapper.selectOption(appClient);
    }

    @Override
    public AppInfo portal(String appCode) {
        AppInfo appInfo = baseMapper.getOneNoTenant(new QueryWrapper<AppInfo>().eq("app_code",appCode));
        if(ObjectUtil.isNotEmpty(appInfo)){
            appInfo.setAppLogo(appInfo.getAppLogo());
            if(StrUtil.isNotBlank(appInfo.getAppImage())){
                String[] imageArr = appInfo.getAppImage().split(",");
                List<String> imageList = new ArrayList<>();
                for(String item :imageArr){
                    imageList.add(item);
                }
                appInfo.setImageList(imageList);
            }
            //客户端列表
            List<AppClient> clientList = clientMapper
                    .selectListNoTenant(new QueryWrapper<AppClient>().eq("info_id", appInfo.getId()));
            if(ObjectUtil.isNotEmpty(clientList)){
                List<Long> clientIds = clientList.stream().map(AppClient::getId).collect(Collectors.toList());
                List<AppUpgrade> latestList = upgradeMapper.latestRecords(clientIds); //获取最新版本
                clientList.forEach(item->{
                    if(StrUtil.isNotBlank(item.getPlatformType())){
                        AppPlatformTypeEnums appPlatformTypeEnums = AppPlatformTypeEnums.getEnumByValue(item.getPlatformType());
                        item.setPlatformTypeTxt(MessageUtils.message(appPlatformTypeEnums.getRemark()));
                    }
                    if(StrUtil.isNotBlank(item.getAppType())){
                        item.setAppTypeTxt(AppTypeEnums.getEnumByValue(item.getAppType()).getLabel());
                    }
                    Optional<AppUpgrade> upgradeOptional = latestList.stream().filter(a-> a.getClientId().equals(item.getId())).findFirst();
                    upgradeOptional.ifPresent(a-> {
                        item.setUrl(a.getUrl());
                    });
                });
                Map<String, List<AppClient>> clientMap = clientList.stream()
                        .collect(Collectors.groupingBy(AppClient::getAppType));
                ArrayNode arrayNode = JacksonUtil.newJSONArray();
                clientMap.forEach((k, v)->{
                    ObjectNode jsonNode = JacksonUtil.newJSONObject();
                    AppTypeEnums appTypeEnums = AppTypeEnums.getEnumByValue(k);
                    jsonNode.put("value", appTypeEnums.getKey());
                    jsonNode.put("label", appTypeEnums.getLabel());
                    JsonNode json = JacksonUtil.parseJSONArray(v);
                    jsonNode.put("result", json);
                    arrayNode.add(jsonNode);
                });
                appInfo.setClientJson(arrayNode);
            }
        }
        return appInfo;
    }
}
